package com.jhte.scheduleJob.job;

import com.jhte.scheduleJob.base.util.ConcurrentDateUtil;
import com.jhte.scheduleJob.entity.QuartzLog;
import com.jhte.scheduleJob.service.QuartzLogService;
import com.jhte.scheduleJob.util.ScheduleConstant;
import com.jhte.scheduleJob.util.SpringContextUtil;
import com.jhte.scheduleJob.util.SpringUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.util.Date;

/**
 * @author wuchun
 * @description 定时任务监听
 * @create 2018/2/6 18:27
 */
public class MonitorJobListener implements JobListener {

    private final Logger logger = Logger.getLogger(MonitorJobListener.class);

    private ThreadLocal<QuartzLog> localLog = new ThreadLocal<QuartzLog>();

    @Override
    public String getName() {
        return "MonitorJobListener";
    }

    @Override
    public void jobToBeExecuted(JobExecutionContext jobExecutionContext) {
        JobDetail jobDetail = jobExecutionContext.getJobDetail();
        JobKey jobKey = jobDetail.getKey();
        QuartzLog quartzLog = new QuartzLog();
        quartzLog.setJobName(jobKey.getName());
        quartzLog.setJobGroup(jobKey.getGroup());
        //设置任务执行类型
        String execType = jobExecutionContext.getMergedJobDataMap().getString("execType");
        if (StringUtils.isNotBlank(execType)) {
            quartzLog.setExecType(execType);
        }
        try {
            quartzLog.setStartTime(ConcurrentDateUtil.formatDate(new Date()));
        } catch (ParseException e) {
            logger.error(MonitorJobListener.class + ":" + e.getMessage());
        }
        try {
            int flag = getService().insertQuartzLog(quartzLog);
            if (flag < 1) {
                logger.error("记录定时任务日志失败|" + quartzLog.getStartTime());
            }
        } catch (Exception e) {
            logger.error("记录定时任务日志失败:" + e.getMessage(), e);
        }
        localLog.set(quartzLog);
    }

    @Override
    public void jobExecutionVetoed(JobExecutionContext jobExecutionContext) {

    }

    @Override
    public void jobWasExecuted(JobExecutionContext jobExecutionContext, JobExecutionException jobException) {
        QuartzLog quartzLog = localLog.get();
        if (null != quartzLog) {
            try {
                quartzLog.setEndTime(ConcurrentDateUtil.formatDate(new Date()));
                quartzLog.setTakesTime(ConcurrentDateUtil.parseStrDate(quartzLog.getEndTime()).getTime() -
                        ConcurrentDateUtil.parseStrDate(quartzLog.getStartTime()).getTime());
            } catch (ParseException e1) {
                logger.error(MonitorJobListener.class + ":" + jobException.getMessage());
            }
            if (jobException != null) {
                //出现异常
                quartzLog.setExecStatus(ScheduleConstant.EXECSTATUS_FAIL);
                quartzLog.setMessage(jobException.getMessage());
            }
            try {
                int flag = getService().updateQuartzLog(quartzLog);
                if (flag < 1) {
                    logger.error("更新定时任务日志失败|" + quartzLog.getEndTime());
                }
            } catch (Exception e) {
                logger.error("更新定时任务日志失败:" + e.getMessage(), e);
            }
        } else {
            logger.error("更新定时任务日志失败|" + quartzLog.getEndTime());
        }
        if (jobException != null) {
            logger.error("Fail to execute ScheduleJob !", jobException);
        }
    }

    private QuartzLogService getService() {
        return SpringContextUtil.getBean(QuartzLogService.class);
    }
}